﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web;
using System.Collections;
using System.Web.SessionState;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Globalization;
using AjaxControlToolkit;
public partial class Main_Item_ItemView : System.Web.UI.Page
{
    #region Declare Variable for Page
    Datautility dut = new Datautility();
    CommonLog ObjComLog = new CommonLog();
    DataTable MyDT = new DataTable();
    int ControlCounter = 4;
    int count = 1;
    int mpnCounter = 3;
    string ItemDescription = "";
    string UserId = "";
    string Username = "";
    #endregion
    #region Declare List for Add new Row
    List<string> LstID;
    List<string> LstMPNNo;
    List<string> LstAJAXMPNNO;
    List<string> LstMPNName;
    List<string> LstMFRLTime;
    List<string> LstTransitLTime;
    List<string> LstTotalLTime;
    List<string> LstD1;
    List<string> LstD2;
    List<string> LstD3;
    #endregion
    #region Webservice for the Item Code And the MPN number
    [System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]
    public static List<string> GetItemCode(string prefixText)
    {
        Datautility db = new Datautility();
        DataTable dt = db.getdata("Select ITMCODE from IVR_ITEM where ITMCODE like '%" + prefixText + "%' order by ITMCODE DESC");
        List<string> ItemDesc = new List<string>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ItemDesc.Add(Convert.ToString(dt.Rows[i]["ITMCODE"].ToString()));
        }
        return ItemDesc;
    }
    [System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]
    public static List<string> GetMpnCode(string prefixText)
    {
        Datautility db = new Datautility();
        DataTable dt = db.getdata("select top 10 MPNCODE,IVR_ITEM.ITMDESC as ItemName from IVR_ITEM_MPN inner join IVR_ITEM on IVR_ITEM_MPN.ITEMID=IVR_ITEM.ITMID where MPNCODE like '%" + prefixText + "%'");
        List<string> MPNCode = new List<string>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            MPNCode.Add(Convert.ToString(dt.Rows[i]["MPNCODE"].ToString()));
        }
        return MPNCode;
    }
    #endregion
    #region For the Viewstate of the Row Created
    protected override void LoadViewState(object savedState)
    {
        try
        {
            base.LoadViewState(savedState);
            LstID = (List<string>)ViewState["LstID"];
            LstMPNNo = (List<string>)ViewState["LstMPNNo"];
            LstAJAXMPNNO = (List<string>)ViewState["LstAJAXMPNNO"];
            LstMPNName = (List<string>)ViewState["LstMPNName"];
            LstMFRLTime = (List<string>)ViewState["LstMFRLTime"];
            LstD1 = (List<string>)ViewState["LstD1"];
            LstTransitLTime = (List<string>)ViewState["LstTransitLTime"];
            LstD2 = (List<string>)ViewState["LstD2"];
            LstTotalLTime = (List<string>)ViewState["LstTotalLTime"];
            LstD3 = (List<string>)ViewState["LstD3"];
            if (LstID != null)
            {
                int count = Convert.ToInt32(LstID.Count.ToString());
                for (int i = 0; i < count; i++)
                {
                    mpnCounter++;
                    Label lbl = new Label();
                    lbl.ID = LstID[i].ToString();
                    lbl.Text = mpnCounter.ToString();

                    HtmlTableRow htrow = new HtmlTableRow();
                    htrow.ID = "htrow" + mpnCounter.ToString();

                    HtmlTableCell htcell1 = new HtmlTableCell();
                    htcell1.ID = "htcell1" + mpnCounter.ToString();
                    htcell1.Width = "19%";
                    TextBox txtmanufacturecode = new TextBox();
                    txtmanufacturecode.ID = LstMPNNo[i].ToString();
                    txtmanufacturecode.CssClass = "input";
                    txtmanufacturecode.MaxLength = 50;
                    txtmanufacturecode.Attributes.Add("onblur", "checkduplicate(this);");
                    txtmanufacturecode.Width = Unit.Percentage(70);
                    txtmanufacturecode.AutoPostBack = true;
                    txtmanufacturecode.TextChanged += new EventHandler(txtmanufacturecode_TextChanged);
                    //Adding Ajax Control
                    AjaxControlToolkit.AutoCompleteExtender ACEMPNCODE = new AjaxControlToolkit.AutoCompleteExtender();
                    ACEMPNCODE.ID = LstAJAXMPNNO[i].ToString();
                    ACEMPNCODE.ServiceMethod = "GetMpnCode";
                    ACEMPNCODE.MinimumPrefixLength = 1;
                    ACEMPNCODE.CompletionInterval = 0;
                    ACEMPNCODE.CompletionListCssClass = "AutoExtender";
                    ACEMPNCODE.CompletionListItemCssClass = "AutoExtenderList";
                    ACEMPNCODE.CompletionListHighlightedItemCssClass = "AutoExtenderHighlight";
                    ACEMPNCODE.EnableCaching = false;
                    ACEMPNCODE.TargetControlID = txtmanufacturecode.ID;

                    htcell1.Controls.Add(ACEMPNCODE);
                    htcell1.Controls.Add(txtmanufacturecode);

                    HtmlTableCell htcell2 = new HtmlTableCell();
                    htcell2.ID = "htcell2" + mpnCounter.ToString();
                    htcell2.Width = "19%";
                    DropDownList ddlManufacturer = new DropDownList();
                    ddlManufacturer.ID = LstMPNName[i].ToString();
                    ddlManufacturer.Width = Unit.Percentage(70);
                    ddlManufacturer.CssClass = "dropdown";
                    htcell2.Controls.Add(ddlManufacturer);

                    HtmlTableCell htcell3 = new HtmlTableCell();
                    htcell3.ID = "htcell3" + mpnCounter.ToString();
                    htcell3.Width = "19%";
                    TextBox txtmfrleadtime = new TextBox();
                    txtmfrleadtime.ID = LstMFRLTime[i].ToString();
                    txtmfrleadtime.CssClass = "input";
                    txtmfrleadtime.MaxLength = 12;
                    txtmfrleadtime.Width = Unit.Percentage(70);
                    txtmfrleadtime.Attributes.Add("onblur", "calcLeadTime();");
                    Label lblleadtime = new Label();
                    lblleadtime.ID = LstD1[i].ToString();
                    lblleadtime.Text = "(D)";

                    htcell3.Controls.Add(txtmfrleadtime);
                    htcell3.Controls.Add(lblleadtime);

                    HtmlTableCell htcell4 = new HtmlTableCell();
                    htcell4.ID = "htcell4" + mpnCounter.ToString();
                    htcell4.Width = "19%";
                    TextBox txttransitleadtime = new TextBox();
                    txttransitleadtime.ID = LstTransitLTime[i].ToString();
                    txttransitleadtime.CssClass = "input";
                    txttransitleadtime.MaxLength = 12;
                    txttransitleadtime.Width = Unit.Percentage(70);
                    txttransitleadtime.Attributes.Add("onblur", "calcLeadTime();");
                    Label lblTransittotal = new Label();
                    lblTransittotal.ID = LstD2[i].ToString();
                    lblTransittotal.Text = "(D)";
                    htcell4.Controls.Add(txttransitleadtime);
                    htcell4.Controls.Add(lblTransittotal);

                    HtmlTableCell htcell5 = new HtmlTableCell();
                    htcell5.ID = "htcell5" + mpnCounter.ToString();
                    htcell5.Width = "19%";
                    TextBox txttotalleadtime = new TextBox();
                    txttotalleadtime.ID = LstTotalLTime[i].ToString();
                    txttotalleadtime.Width = Unit.Percentage(70);
                    txttotalleadtime.ReadOnly = true;
                    txttotalleadtime.Attributes.Add("onkeypress", "return isNumberKey(this.id,event)");
                    txttotalleadtime.CssClass = "input";
                    txttotalleadtime.Style["background-color"] = "LightGray";
                    Label lbltotal = new Label();
                    lbltotal.ID = LstD3[i].ToString();
                    lbltotal.Text = "(D)";
                    htcell5.Controls.Add(txttotalleadtime);
                    htcell5.Controls.Add(lbltotal);

                    htrow.Cells.Add(htcell1);
                    htrow.Cells.Add(htcell2);
                    htrow.Cells.Add(htcell3);
                    htrow.Cells.Add(htcell4);
                    htrow.Cells.Add(htcell5);
                    tblMPN.Rows.Add(htrow);
                }
            }
        }
        catch (Exception ex)
        {
        }
    }
    protected void CreateNewRow()
    {
        try
        {
            mpnCounter++;
            Label lbl = new Label();
            lbl.ID = "lbl" + mpnCounter.ToString();
            lbl.Text = mpnCounter.ToString();
            LstID.Add(lbl.Text);

            HtmlTableRow htrow = new HtmlTableRow();
            htrow.ID = "htrow" + mpnCounter.ToString();

            HtmlTableCell htcell1 = new HtmlTableCell();
            htcell1.ID = "htcell1" + mpnCounter.ToString();
            htcell1.Width = "19%";
            TextBox txtmanufacturecode = new TextBox();
            txtmanufacturecode.ID = "txtmanufacturecode" + mpnCounter.ToString();
            txtmanufacturecode.Attributes.Add("onblur", "checkduplicate(this);");
            txtmanufacturecode.AutoPostBack = true;
            txtmanufacturecode.CssClass = "input";
            txtmanufacturecode.MaxLength = 50;
            txtmanufacturecode.TextChanged += new EventHandler(txtmanufacturecode_TextChanged);
            txtmanufacturecode.Width = Unit.Percentage(70);
            //Adding Ajax Control
            AjaxControlToolkit.AutoCompleteExtender ACEMPNCODE = new AjaxControlToolkit.AutoCompleteExtender();
            ACEMPNCODE.ID = "ACEMPNCODE" + mpnCounter.ToString();
            ACEMPNCODE.ServiceMethod = "GetMpnCode";
            ACEMPNCODE.MinimumPrefixLength = 1;
            ACEMPNCODE.CompletionInterval = 0;
            ACEMPNCODE.CompletionListCssClass = "AutoExtender";
            ACEMPNCODE.CompletionListItemCssClass = "AutoExtenderList";
            ACEMPNCODE.CompletionListHighlightedItemCssClass = "AutoExtenderHighlight";
            ACEMPNCODE.EnableCaching = false;
            ACEMPNCODE.TargetControlID = txtmanufacturecode.ID;

            htcell1.Controls.Add(ACEMPNCODE);
            htcell1.Controls.Add(txtmanufacturecode);
            LstMPNNo.Add(txtmanufacturecode.ID);
            LstAJAXMPNNO.Add(ACEMPNCODE.ID);

            HtmlTableCell htcell2 = new HtmlTableCell();
            htcell2.ID = "htcell2" + mpnCounter.ToString();
            htcell2.Width = "19%";
            DropDownList ddlManufacturer = new DropDownList();
            ddlManufacturer.ID = "ddlManufacturer" + mpnCounter.ToString();
            ddlManufacturer.Width = Unit.Percentage(70);
            ddlManufacturer.CssClass = "dropdown";
            htcell2.Controls.Add(ddlManufacturer);
            LstMPNName.Add(ddlManufacturer.ID);

            HtmlTableCell htcell3 = new HtmlTableCell();
            htcell3.ID = "htcell3" + mpnCounter.ToString();
            htcell3.Width = "19%";
            TextBox txtmfrleadtime = new TextBox();
            txtmfrleadtime.ID = "txtmfrleadtime" + mpnCounter.ToString();
            txtmfrleadtime.Width = Unit.Percentage(70);
            txtmfrleadtime.CssClass = "input";
            txtmfrleadtime.MaxLength = 12;
            txtmfrleadtime.Attributes.Add("onblur", "calcLeadTime();");
            htcell3.Controls.Add(txtmfrleadtime);

            Label lblleadtime = new Label();
            lblleadtime.ID = "lblleadtime" + mpnCounter.ToString();
            lblleadtime.Text = "(D)";
            htcell3.Controls.Add(lblleadtime);

            LstMFRLTime.Add(txtmfrleadtime.ID);
            LstD1.Add(lblleadtime.ID);

            HtmlTableCell htcell4 = new HtmlTableCell();
            htcell4.ID = "htcell4" + mpnCounter.ToString();
            htcell4.Width = "19%";
            TextBox txttransitleadtime = new TextBox();
            txttransitleadtime.ID = "txttransitleadtime" + mpnCounter.ToString();
            txttransitleadtime.Width = Unit.Percentage(70);
            txttransitleadtime.CssClass = "input";
            txttransitleadtime.MaxLength = 12;
            txttransitleadtime.Attributes.Add("onblur", "calcLeadTime();");
            htcell4.Controls.Add(txttransitleadtime);

            Label lblTransittotal = new Label();
            lblTransittotal.ID = "lblTransittotal" + mpnCounter.ToString();
            lblTransittotal.Text = "(D)";
            htcell4.Controls.Add(lblTransittotal);

            LstTransitLTime.Add(txttransitleadtime.ID);
            LstD2.Add(lblTransittotal.ID);

            HtmlTableCell htcell5 = new HtmlTableCell();
            htcell5.ID = "htcell5" + mpnCounter.ToString();
            htcell5.Width = "19%";
            TextBox txttotalleadtime = new TextBox();
            txttotalleadtime.ID = "txttotalleadtime" + mpnCounter.ToString();
            txttotalleadtime.Width = Unit.Percentage(70);
            txttotalleadtime.ReadOnly = true;
            txttotalleadtime.Attributes.Add("onkeypress", "return isNumberKey(this.id,event)");
            txttotalleadtime.CssClass = "input";
            txttotalleadtime.Style["background-color"] = "LightGray";
            htcell5.Controls.Add(txttotalleadtime);

            Label lbltotal = new Label();
            lbltotal.ID = "lbltotal" + mpnCounter.ToString();
            lbltotal.Text = "(D)";
            htcell5.Controls.Add(lbltotal);
            LstTotalLTime.Add(txttotalleadtime.ID);
            LstD3.Add(lbltotal.ID);

            htrow.Cells.Add(htcell1);
            htrow.Cells.Add(htcell2);
            htrow.Cells.Add(htcell3);
            htrow.Cells.Add(htcell4);
            htrow.Cells.Add(htcell5);
            tblMPN.Rows.Add(htrow);

            ViewState["LstID"] = LstID;
            ViewState["LstMPNNo"] = LstMPNNo;
            ViewState["LstAJAXMPNNO"] = LstAJAXMPNNO;
            ViewState["LstMPNName"] = LstMPNName;
            ViewState["LstMFRLTime"] = LstMFRLTime;
            ViewState["LstD1"] = LstD1;
            ViewState["LstTransitLTime"] = LstTransitLTime;
            ViewState["LstD2"] = LstD2;
            ViewState["LstTotalLTime"] = LstTotalLTime;
            ViewState["LstD3"] = LstD3;
            HidMPNControl.Value = mpnCounter.ToString();
            GetManufacturer();
        }
        catch (Exception ex)
        {
        }
    }
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["userid"] == null)
            {
                Response.Redirect("~/SessionExpired.aspx");
            }
            else
            {
                string Pagepermission = "select PAGE_ID,PAGE_ADD,PAGE_VIEW,USERID,USERNAME as EmailID from USER_PERMISSION inner join LOGIN on USER_PERMISSION.USER_ID=LOGIN.USERID where USER_ID='" + Session["userid"].ToString() + "' and PAGE_ID=407";
                DataTable dt = dut.getdata(Pagepermission);
                if (dt.Rows.Count > 0)
                {
                    if (Request.QueryString["action"] != null)
                    {                        
                        if (Request.QueryString["action"].ToString() == "addnew")
                        {
                            if (dt.Rows[0]["PAGE_ADD"].ToString() == "True")
                            {
                                PnlAddNew.Visible = true;
                                PnlPaging.Visible = false;
                                try
                                {
                                    if (!IsPostBack)
                                    {
                                        #region
                                        LstID = new List<string>();
                                        ViewState["LstID"] = LstID;
                                        LstMPNNo = new List<string>();
                                        ViewState["LstMPNNo"] = LstMPNNo;
                                        LstAJAXMPNNO = new List<string>();
                                        ViewState["LstAJAXMPNNO"] = LstAJAXMPNNO;
                                        LstMPNName = new List<string>();
                                        ViewState["LstMPNName"] = LstMPNName;
                                        LstMFRLTime = new List<string>();
                                        ViewState["LstMFRLTime"] = LstMFRLTime;
                                        LstD1 = new List<string>();
                                        ViewState["LstD1"] = LstD1;
                                        LstTransitLTime = new List<string>();
                                        ViewState["LstTransitLTime"] = LstTransitLTime;
                                        LstD2 = new List<string>();
                                        ViewState["LstD2"] = LstD2;
                                        LstTotalLTime = new List<string>();
                                        ViewState["LstTotalLTime"] = LstTotalLTime;
                                        LstD3 = new List<string>();
                                        ViewState["LstD3"] = LstD3;
                                        BindItemGroup();
                                        BindCategory();
                                        openingdate();
                                        BindPrimaryUnit();
                                        BindStock();
                                        Itemsettings();
                                        GetManufacturer();
                                        BindDdlUnitOfweight();
                                        BindDdlLocwithdisbatch();
                                        ImagePath.Value = "";
                                        #endregion
                                    }
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                            else
                            {
                                Response.Redirect("~/AccessDenied.aspx");
                            }
                        }                        
                        if (Request.QueryString["action"].ToString() == "view")
                        {
                            if (dt.Rows[0]["PAGE_VIEW"].ToString() == "True")
                            {
                                if (!IsPostBack)
                                {
                                    PnlView.Visible = true;
                                    PnlPaging.Visible = true;
                                    BindItemView();
                                }
                            }
                            else
                            {
                                Response.Redirect("~/AccessDenied.aspx");
                            }
                        }                        
                    }
                }
                if (!IsPostBack)
                {
                    GetProject();
                    this.Close.Attributes.Add("onclick", "Javascript:closeWindows();");
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
            lblMsg.Visible = true;
        }
    }
    #region Method For the Binding Item Master Page
    protected void openingdate()
    {
        for (int i = 1; i < tblopeningbal.Rows.Count; i++)
        {
            TextBox txtOpeningdate = (TextBox)tblopeningbal.Rows[i].FindControl("txtopeningdate");
            int year = System.DateTime.Now.Year;
            txtOpeningdate.Text = year + "-" + "04-01";
        }
    }
    protected void GetManufacturer()
    {
        //string sqlstr = "Select * from MAS_MANUFACTURE order by manufacturename asc";
        string sqlstr = "select * from MAS_MANUFACTURE where ManufactureName != ''  order by manufacturename desc";
        DataTable dt = dut.getdata(sqlstr);
        int count = tblMPN.Rows.Count - 1;
        if (dt.Rows.Count > 0)
        {
            DropDownList DDlManufacturer = new DropDownList();
            if (count > 3)
            {
                DDlManufacturer = (DropDownList)tblMPN.FindControl("ddlManufacturer" + count);
                DDlManufacturer.DataSource = dt;
                DDlManufacturer.DataTextField = "manufactureName";
                DDlManufacturer.DataValueField = "ManufacID";
                DDlManufacturer.DataBind();
                DDlManufacturer.Items.Insert(0, new ListItem("-- Manufacturer --", "0"));
            }
            else
            {
                for (int i = 1; i <= count; i++)
                {
                    DDlManufacturer = (DropDownList)tblMPN.FindControl("ddlManufacturer" + i.ToString());
                    DDlManufacturer.DataSource = dt;
                    DDlManufacturer.DataTextField = "manufactureName";
                    DDlManufacturer.DataValueField = "ManufacID";
                    DDlManufacturer.DataBind();
                    DDlManufacturer.Items.Insert(0, new ListItem("-- Manufacturer --", "0"));
                }
            }
        }
    }
    protected void GetProject()
    {
        string sqlstrprj = "select * from MAS_PROJECT order by projectname asc";
        DataTable dt = dut.getdata(sqlstrprj);
        ddlproject.DataSource = dt;
        ddlproject.DataTextField = "projectname";
        ddlproject.DataValueField = "projectid";
        ddlproject.DataBind();
        ddlproject.Items.Insert(0, new ListItem("-- Select Project Name --", "0"));
    }
    protected void BindDdlUnitOfweight()
    {
        DataTable DT = dut.getdata("select UOMSYMBOL, UOMID from IVR_UOM");
        DdlUnitOfweight.DataSource = DT;
        DdlUnitOfweight.DataTextField = "UOMSYMBOL";
        DdlUnitOfweight.DataValueField = "UOMID";
        DdlUnitOfweight.DataBind();
        DdlUnitOfweight.Items.Insert(0, new ListItem("Select Unit Of Weight", "0"));
    }
    protected void BindDdlLocwithdisbatch()
    {
        for (int i = 1; i <= 2; i++)
        {
            DropDownList ddldeliveryloc = (DropDownList)tblopeningbal.Rows[i].FindControl("ddlloc");
            DataTable dt = dut.getdata("select WHSLOCATION, WHSID from IVR_WAREHOUSE where WHSID=3");
            if (dt.Rows.Count > 0)
            {
                ddldeliveryloc.DataSource = dt;
                ddldeliveryloc.DataTextField = "WHSLOCATION";
                ddldeliveryloc.DataValueField = "WHSID";
                ddldeliveryloc.DataBind();
                //ddldeliveryloc.Items.Insert(0, new ListItem("-- Select Location --", "0"));
            }
        }
    }
    private void BindItemGroup()
    {
        DataTable DT = dut.getdata("Usp_IVR_group");
        if (DT.Rows.Count > 0)
        {
            DDLItemGroup.DataSource = DT;
            DDLItemGroup.DataTextField = "GroupName";
            DDLItemGroup.DataValueField = "igrid";
            DDLItemGroup.DataBind();
            DDLItemGroup.Items.Insert(0, new ListItem("-- Select Item Group --", "0"));
        }
    }
    private void BindStock()
    {
        DataTable DT = dut.getdata("select * from IVR_StockType where stockTypeid=1");
        DDLStockType.DataSource = DT;
        DDLStockType.DataTextField = "StockTypeName";
        DDLStockType.DataValueField = "StockTypeId";
        DDLStockType.DataBind();
        DDLStockType.Items.Insert(0, new ListItem("-- Select Stock Type --", "0"));
    }
    private void BindCategory()
    {
        DataTable DT = dut.getdata("select * from IVR_ITEMCATEGORY where ICAID=2");
        DDLCategory.DataSource = DT;
        DDLCategory.DataTextField = "ICANAME";
        DDLCategory.DataValueField = "ICAID";
        DDLCategory.DataBind();
        //DDLCategory.Items.FindByValue("2").Selected = true;
    }
    private void BindPrimaryUnit()
    {
        DataTable DT = dut.getdata("select UOMSYMBOL, UOMID from IVR_UOM");
        DDLPrimaryUnit.DataSource = DT;
        DDLPrimaryUnit.DataTextField = "UOMSYMBOL";
        DDLPrimaryUnit.DataValueField = "UOMID";
        DDLPrimaryUnit.DataBind();
        DDLPrimaryUnit.Items.Insert(0, new ListItem("-- Select Unit Of Measurement --", "0"));
    }
    protected void Itemsettings()
    {
        string strsql = "select itmcode, itmadditionaldesc, itmaltdesc, ITMALTUNIT, itmupccode, itmbinref from ivr_itemsettings";
        DataTable dt = dut.getdata(strsql);
        if (dt.Rows.Count > 0)
        {
            if (Convert.ToDouble(dt.Rows[0]["ITMALTUNIT"]) > 0)
            {
                DdlAltUnit.Enabled = true;
            }
            else
            {
                DdlAltUnit.Enabled = false;
                DdlAltUnit.BackColor = System.Drawing.ColorTranslator.FromHtml("#ece9d8");
            }
            if (Convert.ToDouble(dt.Rows[0]["itmbinref"]) > 0)
            {

                TxtBillRef.Enabled = true;
            }
            else
            {
                TxtBillRef.Enabled = false;
                TxtBillRef.BackColor = System.Drawing.ColorTranslator.FromHtml("#ece9d8");
            }
            if (Convert.ToDouble(dt.Rows[0]["itmcode"]) > 0)
            {
                TxtItemCode.Enabled = true;
                RFVItemCode.Enabled = true;
            }
            else
            {
                RFVItemCode.Enabled = false;
                TxtItemCode.Enabled = false;
                TxtItemCode.BackColor = System.Drawing.ColorTranslator.FromHtml("#ece9d8");
            }
            if (Convert.ToDouble(dt.Rows[0]["itmaltdesc"]) > 0)
            {
                TxtAlternateDesc.Enabled = true;
            }
            else
            {
                TxtAlternateDesc.Enabled = false;
                TxtAlternateDesc.BackColor = System.Drawing.ColorTranslator.FromHtml("#ece9d8");
            }

            if (Convert.ToDouble(dt.Rows[0]["itmadditionaldesc"]) > 0)
            {
                TxtAdditionalDesc.Enabled = true;
            }
            else
            {
                TxtAdditionalDesc.Enabled = false;
                TxtAdditionalDesc.BackColor = System.Drawing.ColorTranslator.FromHtml("#ece9d8");
            }
        }
    }
    protected void ClearControl()
    {
        TxtItemCode.Text = "";
        TxtItemDescription.Text = "";
        txtlocationid.Text = "";
        txtmanufacturecode1.Text = "";
        TxtMaximum.Text = "0.00";
        TxtMinimum.Text = "0.00";
        TxtReorder.Text = "0.00";
        TxtDimensional.Text = "0.00";
        TxtWeight.Text = "0.00";
        txtmfrleadtime1.Text = "";
        DDLItemGroup.SelectedValue = "0";
        DdlUnitOfweight.SelectedValue = "0";
        DDLPrimaryUnit.SelectedValue = "0";
        ddlManufacturer1.SelectedValue = "0";
        txttransitleadtime1.Text = "";
        txttotalleadtime1.Text = "";
        txtlocationid.Text = "";
        TxtBillRef.Text = "";
        DDLStockType.SelectedValue = "0";
        ddlproject.SelectedValue = "0";
        txtratemain.Text = "";
        txtqtymain.Text = "";
        txtvaluerateqtymain.Text = "";
    }
    protected void BindPrimaryAltUnit()
    {
        DataTable dt = dut.getdata("select  UOMSYMBOL ,UOMID from IVR_UOM where Primary_UOMID =" + DDLPrimaryUnit.SelectedValue.ToString());
        if (dt.Rows.Count > 0)
        {
            DdlAltUnit.DataSource = dt;
            DdlAltUnit.DataTextField = "UOMSYMBOL";
            DdlAltUnit.DataValueField = "UOMID";
            DdlAltUnit.DataBind();
        }
        else
        {
            if (DdlAltUnit.SelectedItem != null)
            {
                DdlAltUnit.SelectedItem.Text = string.Empty;
            }
        }
    }
    #endregion
    #region for the Textchanged event and selected event changed
    protected void TxtItemCode_TextChanged(object sender, EventArgs e)
    {
        if (TxtItemCode.Text != "" || TxtItemCode.Text != null)
        {
            DataTable dtmsg = dut.getdata("select ITMCODE From IVR_ITEM Where ITMCODE ='" + TxtItemCode.Text + "'");
            if (dtmsg.Rows.Count > 0)
            {
                AjaxControlToolkit.ToolkitScriptManager.RegisterStartupScript(Page, GetType(), "ShowAlert", "CheckItemCode();", true);
            }
        }
        else
        {
            TxtItemCode.Text = "";
            TxtItemCode.Focus();
        }
    }
    protected void TxtItemDescription_TextChanged(object sender, EventArgs e)
    {
        //For The Concept of Feet and Inch.
        if (TxtItemDescription.Text !="" || TxtItemDescription.Text!=null)
        {
            if (TxtItemDescription.Text.Contains("'"))
            {
                string abc = TxtItemDescription.Text;
                int temp = abc.IndexOf("'");
                int temp1 = temp + 1;
                ItemDescription = abc.Insert(temp1, "'");
            }
            else
            {
                ItemDescription = TxtItemDescription.Text;
            }
            DataTable dtItemdesc = dut.getdata("select ITMCODE From IVR_ITEM Where ITMDESC ='" + ItemDescription + "'");
            if (dtItemdesc.Rows.Count > 0)
            {
                AjaxControlToolkit.ToolkitScriptManager.RegisterStartupScript(Page, GetType(), "ShowAlert", "CheckItemName()", true);
            }
        }
        else
        {
            TxtItemDescription.Text = "";
            //lblMsg.Text = "Item Code Can not be blank.";
            //lblMsg.Attributes.Add("class", "true");
            TxtItemDescription.Focus();
        }
    }
    protected void DropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList DDL = (DropDownList)sender;
        string ddid = DDL.ID.ToString().Substring(11);
        if (DDL.SelectedValue != "0")
        {
            string item_id = DDL.SelectedValue;
            string sql = "select WHSLOCATION, WHSID from IVR_WAREHOUSE";
            DataTable DT = dut.getdata(sql);
        }
        else
        {
        }
    }
    protected void txtmanufacturecode_TextChanged(object sender, EventArgs e)
    {
        TextBox TxtMpno = (TextBox)sender;
        string mpnno = TxtMpno.ID.ToString().Substring(18);
        int rowIndex = Convert.ToInt32(mpnno.ToString());
        if (TxtMpno.Text != "")
        {
            string FindMpnSql = "select IVR_ITEM.ITMCODE as ItemCode from IVR_ITEM_MPN inner join IVR_ITEM on IVR_ITEM_MPN.ITEMID=IVR_ITEM.ITMID where MPNCODE='" + TxtMpno.Text + "'";
            DataTable DtMpn = dut.getdata(FindMpnSql);
            if (DtMpn.Rows.Count > 0)
            {
                lblMsg.Visible = true;
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = "Mpn No " + TxtMpno.Text + " Is Already With Item Code " + DtMpn.Rows[0]["ItemCode"].ToString();
                TxtMpno.Focus();
            }
        }
    }
    #endregion
    #region Click event of the Page Applyed
    protected void btn_Click(object sender, EventArgs e)
    {
        Response.Redirect("NewItem.aspx");
    }
    protected void Submit_Click(object sender, EventArgs e)
    {
        Submit.Enabled = false;
        string IP = Request.ServerVariables["REMOTE_ADDR"];
        UserId = Session["userid"].ToString();
        Username = Session["username"].ToString();
        string MPNLogDetail = ""; string ItemOtherLogDetail = "";
        string ItemAlternateUOMLog = ""; string OpeningBalanceLog = "";
        string ItemMasterlog = "";
        //For the Concept of Inch And Feet.
        if (TxtItemDescription.Text != "")
        {
            if (TxtItemDescription.Text.Contains("'"))
            {
                string abc = TxtItemDescription.Text;
                int temp = abc.IndexOf("'");
                int temp1 = temp + 1;
                ItemDescription = abc.Insert(temp1, "");
            }
            else
            {
                ItemDescription = TxtItemDescription.Text;
            }
        }
        else
        {
            ItemDescription = TxtItemDescription.Text;
        }

        try
        {
            string fileimage = ""; string alternateUOM = "";
            #region CheckImage
            if (fld.HasFile)
            {
                string uniquename = Guid.NewGuid().ToString().Replace("-", string.Empty);
                FileInfo finfo = new FileInfo(fld.PostedFile.FileName);
                string ext = finfo.Extension;
                fileimage = "~/Main/Inventory/Item/Image/" + uniquename + ext;
                fld.SaveAs(Server.MapPath(fileimage));
            }
            else
            {
                string uniquename = Guid.NewGuid().ToString().Replace("-", string.Empty);
                FileInfo finfo = new FileInfo("noimg.jpg");
                string ext = finfo.Extension;
                fileimage = "~/Main/Inventory/Item/Image/" + uniquename + ext;
                fld.SaveAs(Server.MapPath(fileimage));
            }
            #endregion
            string item_code = TxtItemCode.Text;
            string TxtUpcCode = "0"; double op_stock = 0;
            if (TxtItemCode.Enabled == false)//Check for the existing ItemCode.
            {

            }
            else
            {
                #region ItemCode
                if (hidTotalOp.Value != "0")
                {
                    op_stock = Convert.ToDouble(hidTotalOp.Value.Trim());
                }
                if (TxtAlternateDesc.Text == "")
                {
                    TxtAlternateDesc.Text = "0";
                }
                if (TxtAdditionalDesc.Text == "")
                {
                    TxtAdditionalDesc.Text = "0";
                }
                if (DdlAltUnit.SelectedValue == "")
                {
                    alternateUOM = "0";
                }
                #endregion
                #region MainItem
                SqlParameter[] parm ={                                 
                                  new SqlParameter("@ITMCODE",TxtItemCode.Text.Trim()),
                                  new SqlParameter("@ITMDESC",ItemDescription),                                 
                                  new SqlParameter("@ITMALTDESC",TxtAlternateDesc.Text.Trim()),
                                  new SqlParameter("@ITMADDDESC",TxtAdditionalDesc.Text.Trim()),
                                  new SqlParameter("@IGRID",DDLItemGroup.SelectedValue),
                                  new SqlParameter("@ICAID",DDLCategory.SelectedValue),                                  
                                  new SqlParameter("@StockTypeId",DDLStockType.SelectedValue),                                  
                                  new SqlParameter("@UPCSKUHSNCODE", TxtUpcCode),                                  
                                  new SqlParameter("@PRIMARY_UOMID",DDLPrimaryUnit.SelectedValue),
                                  new SqlParameter("@MAXQTY", TxtMaximum.Text.Trim()),
                                  new SqlParameter("@MINQTY", TxtMinimum.Text.Trim()),                                  
                                  new SqlParameter("@REORDERQTY",TxtReorder.Text.Trim()),
                                  new SqlParameter("@OpeningStock",op_stock),
                                  new SqlParameter("@LOCATIONID",txtlocationid.Text.Trim()),
                                  new SqlParameter("@PROJECTID",ddlproject.SelectedValue),                                                                                          
                                  new SqlParameter("@CName", Session["username"].ToString())                                  
                               };
                int result = dut.executeprocedure("usp_insert_IVR_Item", parm);
                //For log
                ItemMasterlog = "Item Code:" + TxtItemCode.Text + ",ItemDesc:" + TxtItemDescription.Text + ",AlternateDesc:" + TxtAlternateDesc.Text + ",AdditionalDesc:" + TxtAdditionalDesc.Text + ",ItemGroup:" + DDLItemGroup.SelectedItem + ",ItemCategory:" + DDLCategory.SelectedItem + ",StockType:" + DDLStockType.SelectedItem + "," + TxtUpcCode + ",PrimaryUnit:" + DDLPrimaryUnit.SelectedItem + ",Maximum:" + TxtMaximum.Text + ",Minimum:" + TxtMinimum.Text + ",Reorder:" + TxtReorder.Text + ",OpeningStock" + op_stock + ",Location:" + txtlocationid.Text + ",Project:" + ddlproject.SelectedItem;
                #endregion
                if (result > 0)
                {
                    #region ItemMPN
                    string Item_id = "SELECT IDENT_CURRENT('IVR_ITEM') AS ITEMID";
                    DataTable Dt = dut.getdata(Item_id);
                    if (Dt.Rows.Count > 0)
                    {
                        Item_id = Dt.Rows[0][0].ToString();
                    }
                    for (int m = 1; m < tblMPN.Rows.Count; m++)
                    {
                        TextBox txtMPNPartNo = (TextBox)tblMPN.Rows[m].FindControl("txtmanufacturecode" + m.ToString());
                        DropDownList ddlMPNName = (DropDownList)tblMPN.Rows[m].FindControl("ddlManufacturer" + m.ToString());
                        TextBox txtMfrLeadtime = (TextBox)tblMPN.Rows[m].FindControl("txtmfrleadtime" + m.ToString());
                        TextBox txttransiteLeadtime = (TextBox)tblMPN.Rows[m].FindControl("txttransitleadtime" + m.ToString());
                        TextBox txttotalleadtime = (TextBox)tblMPN.Rows[m].FindControl("txttotalleadtime" + m.ToString());

                        if (txttotalleadtime.Text == "")
                        {
                            if (txtMfrLeadtime.Text != "" && txttransiteLeadtime.Text != "")
                            {
                                txttotalleadtime.Text = (Convert.ToDecimal(txtMfrLeadtime.Text) + Convert.ToDecimal(txttransiteLeadtime.Text)).ToString();
                            }
                        }
                        SqlParameter[] MPNparam = {
                                                    new SqlParameter("@ITEMID",Item_id),
                                                    new SqlParameter("@MPNCODE",txtMPNPartNo.Text),
                                                    new SqlParameter("@ManufactureID",ddlMPNName.SelectedValue),
                                                    new SqlParameter("@MFRLEADTIME",txtMfrLeadtime.Text),
                                                    new SqlParameter("@TRANSITELTIME",txttransiteLeadtime.Text),
                                                    new SqlParameter("@TOTALLEADTIME",txttotalleadtime.Text),
                                                    new SqlParameter("@cname", Session["username"].ToString()) 
                                                  };
                        int itempn = dut.executeprocedure("USP_IVR_INSERT_MPN", MPNparam);
                        //For log
                        MPNLogDetail += "Item ID:" + Item_id + ",MPNPartNo:" + txtMPNPartNo.Text + ",MPN Name:" + ddlMPNName.SelectedItem + ",MFRLeadTime:" + txtMfrLeadtime.Text + ",TransiteLeadTime:" + txttransiteLeadtime.Text + ",TotalLeadTime:" + txttotalleadtime.Text;
                    }
                    #endregion
                    #region ItemOther
                    SqlParameter[] paramoth = { 
                                                  new SqlParameter("@ITMID",Item_id),
                                              new SqlParameter("@BINREF",TxtBillRef.Text.Trim()),
                                              new SqlParameter("@UNITSIZE", TxtDimensional.Text.Trim()),
                                              new SqlParameter("@UNITWEIGHT", TxtWeight.Text.Trim()),
                                              new SqlParameter("@UNITWEIGHT_UOMID", DdlUnitOfweight.SelectedValue),
                                              new SqlParameter("@IMAGEPATH", fileimage.ToString()),
                                              new SqlParameter("@CName", Session["username"].ToString()) 
                                           };
                    int itemothe = dut.executeprocedure("usp_ivr_Insert_ITEMOTH", paramoth);
                    //For log
                    ItemOtherLogDetail += "ItemId:" + Item_id + ",BinRef:" + TxtBillRef.Text + ",Dimension:" + TxtDimensional.Text + ",Weight:" + TxtWeight.Text + ",UnitOfWeight:" + DdlUnitOfweight.SelectedItem + ",SelectedImageFile:" + fileimage.ToString();
                    #endregion
                    #region ItemAlternateUOM
                    SqlParameter[] paramuom = { 
                                                  new SqlParameter("@ITMID",Item_id),
                                                  new SqlParameter("@UOMID", alternateUOM),                                 
                                                  new SqlParameter("@CName", Session["username"].ToString()) 
                                              };
                    int itemuom = dut.executeprocedure("usp_ivr_insert_ITEMALTUOM", paramuom);
                    //For Log
                    ItemAlternateUOMLog += "ItemID:" + Item_id + ",AlternateUnitofMeasurement:" + alternateUOM;
                    #endregion
                    #region OpeningBalance
                    if (txtvaluerateqtymain.Text == "")
                    {
                        txtvaluerateqtymain.Text = Convert.ToString(Convert.ToDouble(txtqtymain.Text) * Convert.ToDouble(txtratemain.Text));
                    }
                    if (Convert.ToInt32(ddlloc.SelectedValue) > 0 && txtqtymain.Text != "" && txtratemain.Text != "")
                    {
                        SqlParameter[] sparam ={
                                                           new SqlParameter("@ITMID",Item_id),
                                                           new SqlParameter("@WHSID",ddlloc.SelectedValue),
                                                           new SqlParameter("@QUANTITY",txtqtymain.Text),
                                                           new SqlParameter("@RATE",txtratemain.Text),
                                                           new SqlParameter("@LeasedType",ddlLeasedType.SelectedItem.Text),
                                                           new SqlParameter("@AMOUNT",txtvaluerateqtymain.Text),
                                                           new SqlParameter("@OPDATE",txtopeningdate.Text),
                                                           new SqlParameter("@IssueQty","0"),
                                                           new SqlParameter("@RetrunQty","0")
                                                    };
                        dut.executeprocedure("USP_IVR_SaveItemOpeningBalance", sparam);
                        //For Log
                        OpeningBalanceLog += "ItemID:" + Item_id + ",Location:" + ddlloc.SelectedItem + ",Qty:" + txtqtymain.Text + ",Rate:" + txtratemain.Text + ",LeasedType:" + ddlLeasedType.SelectedItem.Text + ",Value:" + txtvaluerateqtymain.Text + ",OpeningDate:" + txtopeningdate.Text;
                    }
                    #endregion
                }
            }
            lblMsg.Attributes.Remove("class");
            lblMsg.Attributes.Add("class", "true");
            lblMsg.Text = "Item created successfully...";
            //Creating log For the item.
            string ItemDetail = "Item Created with Following details:-" + ItemMasterlog + "," + MPNLogDetail + "," + ItemOtherLogDetail + "," + ItemAlternateUOMLog + "," + OpeningBalanceLog;
            ObjComLog.SetItemLogs(UserId, Username, CommonLog.Type.ActivityLog.ToString(), ItemDetail, "Item.aspx", IP, System.DateTime.Now.ToString());
            ClearControl();
            Response.Redirect("Item.aspx?action=addnew");
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }
    protected void Close_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["view"] == "458723")
        {
            //Close.Attributes.Add("OnClick", "window.close();return true;");
            Page.ClientScript.RegisterStartupScript(GetType(), "CloseScript", "Javascript:closeWindows();", true);
        }
        else
        {
            Response.Redirect("~/Welcome.aspx");
        }
    }
    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        CreateNewRow();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            MyDT.Clear();
            BindItemView();
            string Filter = "";
            string searchvalue = txtvalue.Text.Trim();
            if (ddlColumn.SelectedValue == "1")//for Item Code
            {
                Filter = string.Format(CultureInfo.InvariantCulture, "ITMCODE like'%" + searchvalue + "%'");
                GridItemView.AllowPaging = false;
            }
            else if (ddlColumn.SelectedValue == "2")//for Bin Reference
            {
                Filter = string.Format(CultureInfo.InvariantCulture, "BinREF like'%" + searchvalue + "%'");
                GridItemView.AllowPaging = false;
            }
            else if (ddlColumn.SelectedValue == "3")//for Item Name
            {
                Filter = string.Format(CultureInfo.InvariantCulture, "ITMDESC like'%" + searchvalue + "%'");
                GridItemView.AllowPaging = false;
            }
            else if (ddlColumn.SelectedValue == "4")//for Alt Item Code
            {
                Filter = string.Format(CultureInfo.InvariantCulture, "ALTITEMCODE like'%" + searchvalue + "%'");
                GridItemView.AllowPaging = false;
            }
            //else if (ddlColumn.SelectedValue == "5")//for MPN
            //{
            //    Filter = string.Format(CultureInfo.InvariantCulture, "Manufacturecode like'%" + searchvalue + "%'");
            //    GridItemView.AllowPaging = false;
            //}
            else if (ddlColumn.SelectedValue == "6")//for Project
            {
                Filter = string.Format(CultureInfo.InvariantCulture, "Projectname like'%" + searchvalue + "%'");
                GridItemView.AllowPaging = false;
            }
            DataRow[] Dr = MyDT.Select(Filter);
            DataTable Tempdt = new DataTable();
            Tempdt = MyDT.Clone();
            foreach (DataRow drNew in Dr)
            {
                Tempdt.ImportRow(drNew);
            }
            GridItemView.DataSource = Tempdt;
            GridItemView.DataBind();
            GridItemView.AllowPaging = true;
        }
        catch (Exception ex)
        {
        }
    }
    protected void imgxl_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            DataTable dt = dut.getdatausingprocedure("USP_GetAllItemDetails");
            if (dt.Rows.Count > 0)
            {
                grditemexcel.DataSource = dt;
                grditemexcel.DataBind();
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Item-Detail.xls"));
                Response.ContentType = "application/ms-excel";
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                grditemexcel.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.End();
            }
        }
        catch (Exception ex)
        {

        }
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }
    #endregion
    #region For the Gridview of the Page
    private void BindItemView()
    {
        try
        {
            DataTable dt = dut.getdatausingprocedure("usp_ivr_get_all_items_maindetails");
            MyDT.Columns.Add("ITMID", typeof(string));
            MyDT.Columns.Add("ITMCODE", typeof(string));
            MyDT.Columns.Add("ITMDESC", typeof(string));
            MyDT.Columns.Add("ALTITEMCODE", typeof(string));
            MyDT.Columns.Add("IGRID", typeof(string));
            MyDT.Columns.Add("PRIMARYUOMID", typeof(string));
            MyDT.Columns.Add("OpeningStock", typeof(string));
            MyDT.Columns.Add("reorderqty", typeof(string));
            MyDT.Columns.Add("Projectname", typeof(string));
            MyDT.Columns.Add("locationid", typeof(string));
            MyDT.Columns.Add("BinREF", typeof(string));
            MyDT.Columns.Add("location", typeof(string));
            MyDT.Columns.Add("IMAGEPATH", typeof(string));
            MyDT.Columns.Add("ITMACTIVE", typeof(string));
            MyDT.Columns.Add("LEASEDTYPE", typeof(string));
            MyDT.Columns.Add("QTY", typeof(string));
            MyDT.Columns.Add("RATE", typeof(string));
            MyDT.Columns.Add("VALUE", typeof(string));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow DR = MyDT.NewRow();
                DR["ITMID"] = dt.Rows[i]["ITMID"];
                DR["ITMCODE"] = dt.Rows[i]["ITMCODE"];
                DR["ITMDESC"] = dt.Rows[i]["ITMDESC"];
                DR["ALTITEMCODE"] = dt.Rows[i]["ALTITEMCODE"];
                DR["IGRID"] = dt.Rows[i]["IGRID"];
                DR["PRIMARYUOMID"] = dt.Rows[i]["PRIMARYUOMID"];
                DR["reorderqty"] = Convert.ToDouble(dt.Rows[i]["reorderqty"]).ToString("N1");
                DR["Projectname"] = dt.Rows[i]["Projectname"];
                DR["locationid"] = dt.Rows[i]["locationid"];
                DR["BinREF"] = dt.Rows[i]["BinREF"];
                DR["location"] = dt.Rows[i]["location"];
                DR["LEASEDTYPE"] = dt.Rows[i]["LeasedType"];
                DR["QTY"] = Convert.ToDouble(dt.Rows[i]["quantity"]).ToString("N0");
                DR["RATE"] = dt.Rows[i]["rate"];
                DR["VALUE"] = dt.Rows[i]["amount"];
                if (dt.Rows[i]["OpeningStock"].ToString() != "")
                {
                    DR["OpeningStock"] = Convert.ToDouble(dt.Rows[i]["OpeningStock"]).ToString("N2");
                }
                string ITMACTIVE = dt.Rows[i]["ITMACTIVE"].ToString();
                if (ITMACTIVE == "True")
                {
                    DR["ITMACTIVE"] = "Yes";
                }
                else
                {
                    DR["ITMACTIVE"] = "No";
                }
                string url;
                string[] splitsurl = Request.Url.AbsoluteUri.Split('/');
                if (splitsurl.Length >= 2)
                {
                    url = splitsurl[0] + "/";
                    for (int j = 2; j < splitsurl.Length - 4; j++)
                    {
                        url += "/";
                        url += splitsurl[j];
                    }
                    string[] Path = dt.Rows[i]["IMAGEPATH"].ToString().Split('~');
                    if (Path[1].ToString() != "")
                    {
                        DR["IMAGEPATH"] = url + Path[1];
                    }
                }
                MyDT.Rows.Add(DR);
            }
            GridItemView.DataSource = MyDT;
            GridItemView.DataBind();
            GridItemView.EnableViewState = false;
        }
        catch (Exception ex)
        {
            lblMsg.Visible = false;
            lblMsg.Text = ex.Message;
        }
    }
    protected void GridItemView_RowCreated(object sender, GridViewRowEventArgs e)
    {

    }
    protected void GridItemView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HiddenField hdfield = (HiddenField)e.Row.FindControl("hidactive");
            string ITMID = GridItemView.DataKeys[e.Row.RowIndex].Value.ToString();
            if (hdfield.Value == "No")
            {
                e.Row.BackColor = System.Drawing.Color.LightPink;
            }
            GridView GrdMPNChild = (GridView)e.Row.FindControl("gvItemChild");
            string SqlMpn = "Select ISNULL(MPNCODE,'--') as Manufacturecode,M.manufactureName as ManufactureName, ISNULL(MFRLEADTIME,'--') as MFRLEADTIME,ISNULL(TOTALLEADTIME,'--') as TOTALLEADTIME,ISNULL(TRANSITELTIME,'--') as TRANSITLTIME from IVR_ITEM_MPN IM inner join MAS_MANUFACTURE M on M.ManufacID=IM.ManufacturerID where IM.ITEMID=" + ITMID;
            DataTable DTMPNDetails = dut.getdata(SqlMpn);
            DataTable DTMPN = new DataTable();
            DTMPN.Columns.Add("Manufacturecode", typeof(string));
            DTMPN.Columns.Add("ManufactureName", typeof(string));
            DTMPN.Columns.Add("MFRLEADTIME", typeof(string));
            //DTMPN.Columns.Add("TOTALLEADTIME", typeof(string));
            DTMPN.Columns.Add("TRANSITLTIME", typeof(string));
            if (DTMPNDetails.Rows.Count > 0)
            {
                for (int i = 0; i < DTMPNDetails.Rows.Count; i++)
                {
                    DataRow DR = DTMPN.NewRow();
                    DR["Manufacturecode"] = DTMPNDetails.Rows[i]["Manufacturecode"].ToString();
                    DR["ManufactureName"] = DTMPNDetails.Rows[i]["ManufactureName"].ToString();
                    DR["MFRLEADTIME"] = DTMPNDetails.Rows[i]["MFRLEADTIME"].ToString();
                    //DR["TOTALLEADTIME"] = DTMPNDetails.Rows[i]["TOTALLEADTIME"].ToString();
                    DR["TRANSITLTIME"] = DTMPNDetails.Rows[i]["TRANSITLTIME"].ToString();
                    DTMPN.Rows.Add(DR);
                }
            }
            GrdMPNChild.DataSource = DTMPN;
            GrdMPNChild.DataBind();
        }
    }
    protected void GridItemView_DataBound(object sender, EventArgs e)
    {
        //for (int rowIndex = GridItemView.Rows.Count - 2;rowIndex >= 0; rowIndex--)
        //{
        //    GridViewRow gvRow = GridItemView.Rows[rowIndex];
        //    GridViewRow gvPreviousRow = GridItemView.Rows[rowIndex + 1];
        //    for (int cellCount = 0; cellCount < gvRow.Cells.Count; cellCount++)
        //    {
        //        if (gvRow.Cells[cellCount].Text != "" && gvPreviousRow.Cells[cellCount].Text != "")
        //        {
        //            if (gvRow.Cells[cellCount].Text == gvPreviousRow.Cells[cellCount].Text)
        //            {
        //                if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
        //                {
        //                    gvRow.Cells[cellCount].RowSpan = 2;
        //                }
        //                else
        //                {
        //                    gvRow.Cells[cellCount].RowSpan = gvPreviousRow.Cells[cellCount].RowSpan + 1;
        //                }
        //                gvPreviousRow.Cells[cellCount].Visible = false;
        //            }
        //        }
        //    }
        //}
    }
    protected void GridItemView_SelectedIndexChanged(object sender, EventArgs e)
    {
        string ITMID = GridItemView.SelectedDataKey.Value.ToString();
        Response.Redirect("NewItemEdit.aspx?ITMID=" + ITMID);
    }
    protected void GridItemView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridItemView.PageIndex = e.NewPageIndex;
        BindItemView();
    }
    #endregion
    #region Other Part of the Page
    //protected void DDLCategory_DataBound(object sender, EventArgs e)
    //{
    //    DropDownList ddl = sender as DropDownList;
    //    if (ddl != null)
    //    {
    //        foreach (ListItem li in ddl.Items)
    //        {
    //            li.Attributes["ICANAME"] = li.Text;
    //        }
    //    }
    //}
    //    protected void grdview_RowDataBound(object sender, GridViewRowEventArgs e)
    //{
    //    //if (e.Row.RowType == DataControlRowType.DataRow)
    //    //{
    //    //    FormView FV = (FormView)e.Row.FindControl("frmdetail");
    //    //    int ITEMID = Convert.ToInt32(e.Row.Cells[1].Text);
    //    //    string sql = "select * from IVR_ITEM inner join IVR_ITEMOTH on IVR_ITEMOTH.ITMID=IVR_ITEM.ITMID inner join IVR_ITEMOPENBAL on IVR_ITEMOPENBAL.ITMID=IVR_ITEM.ITMID where IVR_ITEM.ITMID=" + ITEMID;
    //    //    DataTable dtdetail = dut.getdata(sql);
    //    //    if (dtdetail.Rows.Count > 0)
    //    //    {
    //    //        FV.DataSource = dtdetail;
    //    //        FV.DataBind();
    //    //    }
    //    //    e.Row.Cells[3].Attributes.Add("onmouseover", "tooltip.pop(this, '#demo2_tip" + ITEMID + "')");
    //    //}        
    //}
    //    protected void custPager_PageChanged(object sender, CustomPageChangeArgs e)
    //{
    //    GridItemView.PageSize = e.CurrentPageSize;
    //    GridItemView.PageIndex = e.CurrentPageNumber;
    //    BindItemView();
    //}
    //protected void DDLPrimaryUnit_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    //BindPrimaryAltUnit();        
    //}
    //    protected string GetBatch(string Batchno, string itemId)
    //{
    //    string batchId = string.Empty;
    //    string str = "select BATID From Ivr_Batch where BATNUM='" + Batchno.ToString() + "' and ItmId='" + itemId.ToString() + "'";
    //    DataTable DT = dut.getdata(str);
    //    if (DT.Rows.Count > 0)
    //    {
    //        batchId = DT.Rows[0]["BATID"].ToString();
    //    }
    //    else
    //    {
    //        batchId = "0";
    //    }
    //    return batchId;
    //}
    //    private bool CheckBatch(string Batchno, string itemId)
    //{
    //    string str = "select BATNUM From Ivr_Batch where BATNUM='" + Batchno + "' and ItmId='" + itemId + "'";
    //    DataTable DT = dut.getdata(str);
    //    if (DT.Rows.Count > 0)
    //    {
    //        return false;
    //    }
    //    else
    //    {
    //        return true;
    //    }
    //}
    #endregion
}
